package com.fafi.selfmvc.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/download")
public class DownloadController {
	@RequestMapping("/d1")
	public String downloadFile(HttpServletResponse response) {

		String fileName = "160396245819410029.jpg";
		try {
			//获取页面输出流
			ServletOutputStream outputStream = response.getOutputStream();
			//读取文件
			byte[] bytes = FileUtils.readFileToByteArray(new File("H:\\"+fileName));
			//向输出流写文件
			//写之前设置响应流以附件的形式打开返回值,这样可以保证前边打开文件出错时异常可以返回给前台
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			outputStream.write(bytes);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "success";
	}
}
